// 异常拦截器
import { ExceptionFilter,Catch,ArgumentsHost,HttpException } from "@nestjs/common";
import {Request,Response} from 'express'
import { Logger } from "../utils/log4js";

@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
    catch(exception:HttpException,host:ArgumentsHost) {
        const ctx = host.switchToHttp()
        const request = ctx.getRequest<Request>()
        const response = ctx.getResponse<Response>()
        const status = exception.getStatus()

        const logFormat = 
` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  Request original url: ${request.originalUrl}
  Method: ${request.method}
  IP: ${request.ip}
  Status code: ${status}
  Response: ${exception.toString()}
  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
`
        Logger.error(logFormat)

        response.status(status).json({
            data:exception.getResponse(),
            message:exception.message,
            time:new Date().getTime(),
            success:false,
            path:request.url,
            status
        })
    }
}